﻿using MediatR;
using SmartTracking.ApiRead.Applications.Commands;
using SmartTracking.Domain.EWE;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.ApiRead.Applications.CommandHandlers
{
    public class GetEwematingsQueryCommandHandler : IRequestHandler<GetEwematingsQueryCommand, ApiResult<ApiPaging<Ewematings>>>
    {
        private readonly IBaseRepository<Ewematings> eRep;
        public GetEwematingsQueryCommandHandler(IBaseRepository<Ewematings> eRep)
        {
            this.eRep = eRep;
        }
        public Task<ApiResult<ApiPaging<Ewematings>>> Handle(GetEwematingsQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<Ewematings>>result=new ApiResult<ApiPaging<Ewematings>>();
            result.Code = ApiEnum.查询成功;
            result.Message = "查询成功";

            var list = eRep.GetAll().Where(x=>!x.IsDeleted);

            // 如果指定了配种时间，则进行过滤
            if (request.StartEwematingTime != null)
            {
                list = list.Where(x => x.EwematingTime>= request.StartEwematingTime);
            }if (request.StartEwematingTime != null)
            {
                list = list.Where(x => x.EwematingTime <= request.EndEwematingTime);
            }
            if (request.EwematingSnowId != null)
            {
                list = list.Where(x => x.EwematingSnowId==request.EwematingSnowId);
            }
            if (request.ResponsibleFor != null)
            {
                list = list.Where(x => x.ResponsibleFor==request.ResponsibleFor);
            }

            int totalCount = list.Count();
            int totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(x => x.EwematingId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            ApiPaging<Ewematings> paging = new ApiPaging<Ewematings>();
            paging.totalCount = totalCount;
            paging.totalPage = totalPage;
            paging.data = list.ToList();

            result.data = paging;

            return Task.FromResult(result);
        }
    }
}
